//区域选择
define(['jquery','common','bootstrapselect'], function($,common) {
    $.fn.extend({
        initAreaSelect: function() {
        	//参数和默认值
            var o = {};
            o.$this=this;
            o.area = {};
            //初始化函数
            var init = function() {
            	//level 3 小区,2县区,1市,0省
                var param = $.parseJSON(o.$this.attr("data-param"));
                if(param.id != undefined && param.id != "" && param.pid != undefined && param.pid !="" ){
                	//initCommunity(param.id,);
                	initArea(param.pid,param.id,true)
                }else{//为空取省
                	common.ajax_request('get','/api/v1/queryArea',{pid:1},function(data){
	    				var html = [];
	        			html.push("<li>");
	        			html.push("<select class=\"form-control areaSelClass\" level=\""+data.level+"\">");
	        			html.push("<option value=\"\">请选择...</option>");
	        			$.each(data.dataList, function(i, item) {
	            			html.push("<option value=\""+item.id+"\">"+item.areaName+"</option>");
	        			});
	        			html.push("</select>");
	        			html.push("</li>");
	        			o.$this.html(html.join(""));
                	});
                }
                areaEvent();
            };
            
            var initArea = function(area_id,id,isLastArea){
            	//当前区域，向上取区域
        		common.ajax_request('get','/api/v1/queryArea',{id:area_id},function(data){
        			var pid;
        			var html = [];
            		html.push("<select class=\"form-control areaSelClass\" level=\""+data.level+"\">");
            		html.push("<option value=\"\">请选择...</option>");
	        		$.each(data.dataList, function(i, item) {
                		if(area_id==item.id){
                			pid = item.parent_id;
                			html.push("<option value=\""+item.id+"\" selected=true>"+item.areaName+"</option>");
                		}else{
                			html.push("<option value=\""+item.id+"\">"+item.areaName+"</option>");
                		}
                		if(isLastArea){
                			o.area[item.id.toString()]=item.areaName;
                		}
	        		});
            		html.push("</select>");
            		if(o.$this.find('li:first').length>0){
            			o.$this.find('li:first').before("<li>" + html.join("") + "</li>");
            		}else{
            			o.$this.append("<li>" + html.join("") + "</li>");
            		}
        			if(data.level != 0 && pid != undefined && pid != "undefined"){
        				initArea(pid,id,false)
        			}
        			if(isLastArea){
        				initCommunity(id,area_id);
        				o.pid = pid;
        			}
            	});
            }
            
            var areaEvent = function(){
            	$(document).off('change','.areaSelClass').on('change','.areaSelClass',function(){
            		var id = $(this).val();
            		var level = $(this).attr("level");
            		$(this).parent().nextAll().remove();
            		if(id != "" && level !=2){
	            		common.ajax_request('get','/api/v1/queryArea',{pid:id},function(data){
	        				var html = [];
	            			html.push("<li>");
	            			html.push("<select class=\"form-control areaSelClass\" level=\""+data.level+"\">");
	            			html.push("<option value=\"\">请选择...</option>");
		        			$.each(data.dataList, function(i, item) {
	                			html.push("<option value=\""+item.id+"\">"+item.areaName+"</option>");
	                			if(data.level==2){
		            				o.area[item.id.toString()]=item.areaName;
		            				o.pid = item.pid;
		            			}
		        			});
	            			html.push("</select>");
	            			html.push("</li>");
	            			if(o.$this.find('li:last').find("select:last").val()==id){//所选地区属于当前父节点
	            				o.$this.find('li:last').after(html.join(""));
	            			}
	            			
	            		});
            		}else if(id != "" && level ==2){
            			
            			initCommunity("",id)
            			
            		}
            	});
            }
            
            //初始化小区
            var initCommunity = function(id,area_id){
            	//console.log(area_id);
        		common.ajax_request('get','/api/v1/queryCommunityByAreaId',{area_id:area_id},function(data){
        			var html = [];
        			html.push("<li>");
        			html.push("<select class=\"form-control selectpicker\" level=\"3\" id=\"comm_idbasic\" data-live-search=\"true\">");
        			html.push("<option value=\"\">请选择...</option>");
        			var select_src = "";
        			var isReload = false;
        			$.each(data, function(i, item) {
        				if(id==item.id){
        					html.push("<option value=\""+item.id+"\" data-pid=\""+item.pid+"\" selected=true data-subtext=\""+o.area[item.pid]+"\">"+item.community_name+"</option>");
        					select_src = "<option value=\""+item.id+"\" data-pid=\""+item.pid+"\" selected=true data-subtext=\""+o.area[item.pid]+"\" data-subtext-temp=\""+o.area[item.pid]+"\">"+item.community_name+"</option>";
        				}else{
        					html.push("<option value=\""+item.id+"\" data-pid=\""+item.pid+"\" data-subtext=\""+o.area[item.pid]+"\">"+item.community_name+"</option>");
        				}
            		});
        			html.push("</select>");
        			html.push("</li>");
                     
        			o.$this.append(html.join(""));
        			var comm_idbasic2=$('#comm_idbasic');
        			//comm_idbasic2.selectpicker('render');
        			comm_idbasic2.selectpicker('refresh');
        			//var _t = new Date().getTime();
        			$(".bs-searchbox").on("input",function(event){//添加input框事件
        				console.log("input");
        				var s = "";
            			var timeOut = "";
        				$(".no-results").hide();
        			    s = $(".bs-searchbox input").val();//搜索字符串
        			    console.log("s=="+s);
        			    var tempAjax = [];
			    	    isReload = true;
//    			        clearTimeout(timeOut);
//    			        var timeOut = setTimeout(function(){   //设置延后ajax请求
			    	    
			            common.ajax_request('post','/api/v1/queryCommunityByPidAndName',{area_id:o.pid,area_name:s},function(data){
			        	    tempAjax = [];
			        	    var havSelect = false;
                   			$.each(data, function(i, item) {
                   				if(id==item.id){
                   					havSelect = true;
	                				tempAjax.push("<option value=\""+item.id+"\" data-pid=\""+item.pid+"\" selected=true data-subtext=\""+o.area[item.pid]+"\">"+item.community_name+"</option>");
                   				}else{
	                				tempAjax.push("<option value=\""+item.id+"\" data-pid=\""+item.pid+"\" data-subtext=\""+o.area[item.pid]+"\">"+item.community_name+"</option>");
                   				}
                   			});
                   			if(!havSelect){
                   				tempAjax.push(select_src);
                   			}
	                     	$("#comm_idbasic").empty();
	                     	$("#comm_idbasic").append(tempAjax);    
	                     	//更新内容刷新到相应的位置
	                     	//$('#comm_idbasic').selectpicker('render');
	                     	$('#comm_idbasic').selectpicker('refresh');
			            });
//    			        },0);
        		 });
        			
        			 //打开下拉选择重新获取当前区域数据
        			 $('#comm_idbasic').on('shown.bs.select',function(e){
        				 console.log("shown.bs.select");
        				  if(isReload){
        					  isReload = false;
        					  var _area_id=$('#comm_idbasic').parent().parent().prev().find("select").val();
        					  var _id = $('#comm_idbasic').val();
       			    	   	  common.ajax_request('get','/api/v1/queryCommunityByAreaId',{area_id:_area_id},function(data){
    			    		  tempAjax = [];
                       			$.each(data, function(i, item) {
                       				if(_id==item.id){
		                				tempAjax.push("<option value=\""+item.id+"\" data-pid=\""+item.pid+"\" selected=true >"+item.community_name+"</option>");
		            					select_src = "<option value=\""+item.id+"\" data-pid=\""+item.pid+"\" selected=true data-subtext=\""+o.area[item.pid]+"\">"+item.community_name+"</option>";
                       				}else{
		                				tempAjax.push("<option value=\""+item.id+"\" data-pid=\""+item.pid+"\" data-subtext=\""+o.area[item.pid]+"\">"+item.community_name+"</option>");
                       				}
                        		});
                       			
			                     	$("#comm_idbasic").empty();
			                     	$("#comm_idbasic").append(tempAjax);    
			                     	//更新内容刷新到相应的位置
			                     	//$('#comm_idbasic').selectpicker('render');
			                     	$('#comm_idbasic').selectpicker('refresh');
       			    	   	  });
        				  }
        			 });
        			 
        			 //搜索选中
        			 $('#comm_idbasic').on('rendered.bs.select', function (e) {
       			      	if($(this).find("option:selected").attr("data-pid") !=="" && $(this).find("option:selected").attr("data-pid") !==undefined){
       			      		$('#comm_idbasic').parent().parent().prev().find("select").find("option[value='"+$(this).find("option:selected").attr("data-pid")+"']").attr("selected",true);
       			      	}
        			 });
        			 
        			 $('#comm_idbasic').on('change', function (e) {
     					 select_src = "<option value=\""+$('#comm_idbasic').find("option:selected").attr("value")+"\" data-pid=\""+$('#comm_idbasic').find("option:selected").attr("data-pid")+"\" selected=true data-subtext=\""+$('#comm_idbasic').find("option:selected").attr("data-subtext")+"\">"+$('#comm_idbasic').find("option:selected").html()+"</option>";
     					 id = $('#comm_idbasic').find("option:selected").attr("value");
        			 });
            	});
            }
            //初始化
            init();
        }


    }); 
});
